package com.zm.shop.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zm.shop.common.constants.RabbitMQCons;
import com.zm.shop.goods.entity.GoodsPngEntity;
import com.zm.shop.goods.service.GoodsPngService;
import com.zm.shop.stock.entity.StockEntity;
import com.zm.shop.stock.service.StockService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zm.shop.common.utils.PageUtils;
import com.zm.shop.common.utils.Query;

import com.zm.shop.goods.dao.GoodsDao;
import com.zm.shop.goods.entity.GoodsEntity;
import com.zm.shop.goods.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private GoodsPngService goodsPngService;

    @Autowired
    private StockService stockService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );



        return new PageUtils(page);
    }
    @Override
    public void saveAll(GoodsEntity goodsEntity){ //操作三张表，都插入数据

        //1.插入商品信息
        baseMapper.insert(goodsEntity);
        //2.插入商品图片
        List<GoodsPngEntity> goodsPngEntityList = goodsEntity.getGoodsPngEntityList();//获得商品的所有图片信息
        System.out.println("hhh"+goodsPngEntityList);
        for (GoodsPngEntity goodsPngEntity : goodsPngEntityList) {
            goodsPngEntity.setGid(goodsEntity.getId());
        }
        //保存到图片表里
        goodsPngService.saveBatch(goodsPngEntityList);
        //3.插入商品库存
        goodsEntity.getStockEntity().setGid(goodsEntity.getId());
        stockService.save(goodsEntity.getStockEntity());
        //4.发送消息到MQ
        String goodsEntityJSON = JSON.toJSONString(goodsEntity);
        rabbitTemplate.convertAndSend(RabbitMQCons.GOODS_EXCHANGE,RabbitMQCons.GOODS_ROUTE_KEY,goodsEntityJSON);
    }
}